package com.example.myapplication;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class ProductDetailActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);

        ImageView ivImage = findViewById(R.id.iv_detail_image);
        TextView tvName = findViewById(R.id.tv_detail_name);
        TextView tvDescription = findViewById(R.id.tv_detail_description);
        TextView tvPrice = findViewById(R.id.tv_detail_price);
        Button btnAddToCart = findViewById(R.id.btn_add_to_cart);
        Button btnBuy = findViewById(R.id.btn_buy);
        ImageView ivCartIcon = findViewById(R.id.iv_cart_icon);

        // 接收商品数据
        Intent intent = getIntent();
        String name = intent.getStringExtra("name");
        String description = intent.getStringExtra("description");
        double price = intent.getDoubleExtra("price", 0);
        int imageResId = intent.getIntExtra("imageResId", 0);

        // 显示数据
        ivImage.setImageResource(imageResId);
        tvName.setText(name);
        tvDescription.setText(description);
        tvPrice.setText("¥" + price);

        // 加入购物车逻辑
        btnAddToCart.setOnClickListener(v -> {
            SharedPreferences prefs = getSharedPreferences("cart_prefs", MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            Gson gson = new Gson();

            String cartJson = prefs.getString("cart", null);
            List<Product> cartList;
            if (cartJson == null) {
                cartList = new ArrayList<>();
            } else {
                cartList = gson.fromJson(cartJson, new com.google.gson.reflect.TypeToken<List<Product>>() {}.getType());
            }

            Product product = new Product(name, description, price, imageResId);
            cartList.add(product);

            String newCartJson = gson.toJson(cartList);
            editor.putString("cart", newCartJson);
            editor.apply();

            Toast.makeText(this, "商品已加入购物车", Toast.LENGTH_SHORT).show();
        });

        // 跳转到购物车
        ivCartIcon.setOnClickListener(v -> {
            startActivity(new Intent(this, CartActivity.class));
        });
    }
}